package com.dsteiner.xelavos.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.xelavos.client.domain.User;
import com.dsteiner.xelavos.server.EmailUtil.EmailUtilImpl;
import com.dsteiner.xelavos.server.dao.DataDao;

public class EmailServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(EmailServlet.class.getName());
	private EmailUtil emailUtil = EmailUtilImpl.getInstance();
	private DataDao dataDao = DataDao.dataDao;
	public static Map<String, String> htmlTextMap = new HashMap<String, String>();
	public static Map<String, String> plainTextMap = new HashMap<String, String>();

	public void setDataDao(DataDao dataDao) {
		this.dataDao = dataDao;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			System.out.println("EmailServlet.doGet()");
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		try {
			String userId = req.getParameter("userId");
			String email = req.getParameter("email");
			String htmlText = req.getParameter("htmlText");
			String htmlTextId = req.getParameter("htmlTextId");
			String plainTextId = req.getParameter("plainTextId");
			String plainText = req.getParameter("plainText");
			String subject = req.getParameter("subject");
			boolean checkReceiveReport = StringUtil.isEmpty(req.getParameter("checkReceiveReport"));
			
			if(StringUtil.isEmpty(htmlText)){
				htmlText = htmlTextMap.remove(htmlTextId);
			}
			if(StringUtil.isEmpty(plainText)){
				plainText = plainTextMap.remove(plainTextId);
			}
			
			if(!StringUtil.isEmpty(email)){
				emailUtil.doSendEmail(subject, email, plainText, htmlText);
			}
			else{
				User user = (User) dataDao.getObjectById(userId, User.class);
				if(checkReceiveReport && user.isReceiveReport() != null && !user.isReceiveReport())
					return;
				emailUtil.doSendEmail(subject, user, plainText, htmlText);
			}
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
}